<template>
  <a-form
    ref="stepForm1Ref"
    :model="vdata.settingObject"
    layout="vertical"
    :wrapperCol="{ span: 24 }"
    labelAlign="left"
    :hideRequiredMark="false"
    :rules="settingRules"
    :scrollToFirstError="true"
    style="margin-top: 20px"
  >
    <a-row type="flex" justify="space-between" wrap="true">
      <a-col :span="11">
        <a-form-item label="活动期间每个用户可领取最大数量" name="everyoneMaxNum">
          <a-input-number
            v-model:value="vdata.settingObject['everyoneMaxNum']"
            :disabled="vdata.disabled"
            placeholder="请输入最大数量"
            :precision="0"
            :min="0"
            style="width: 100%"
          />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="卡券周期性中奖限制" name="periodTimes">
          <a-radio-group v-model:value="vdata.settingObject['periodType']" :disabled="vdata.disabled">
            <a-radio :value="0">无限制</a-radio>
            <a-radio :value="1">每天限制</a-radio>
            <a-radio :value="2">每周限制</a-radio>
            <a-radio :value="3">每月限制</a-radio>
          </a-radio-group>
          <template v-if="vdata.settingObject['periodType'] !== 0">
            <a-input-number
              v-model:value="vdata.settingObject['periodTimes']"
              :disabled="vdata.disabled"
              :controls="false"
              style="margin: 0 10px;width: 150px;"
              placeholder="卡券周期性限制次数"
            />次
          </template>
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="同一用户周期性次数限制参与" name="everyonePeriodTimes">
          <a-radio-group v-model:value="vdata.settingObject['everyonePeriodType']" :disabled="vdata.disabled">
            <a-radio :value="0">无限制</a-radio>
            <a-radio :value="1">每天限制</a-radio>
            <a-radio :value="2">每周限制</a-radio>
            <a-radio :value="3">每月限制</a-radio>
          </a-radio-group>
          <template v-if="vdata.settingObject['everyonePeriodType'] !== 0">
            <a-input-number
              v-model:value="vdata.settingObject['everyonePeriodTimes']"
              :disabled="vdata.disabled"
              :controls="false"
              style="margin: 0 10px;width: 150px;"
              placeholder="同一用户周期性限制次数"
            />次
          </template>
        </a-form-item>
      </a-col>
      <a-col :span="11">
        <a-form-item label="核销后奖励福分" name="verifiedScore">
          <a-input-number
            v-model:value="vdata.settingObject['verifiedScore']"
            :disabled="vdata.disabled"
            placeholder="请输入核销后奖励福分数"
            :precision="0"
            min="0"
            style="width: 100%"
          />
        </a-form-item>
      </a-col>
      <a-col v-if="vdata.settingObject['verifiedScore'] > 0" :span="11">
        <a-form-item label="福分过期规则类型" name="scoreOverType">
          <a-select
            v-model:value="vdata.settingObject['scoreOverType']"
            :disabled="vdata.disabled"
            placeholder="请选择福分过期规则类型"
            allowClear
          >
            <a-select-option :value="0">n天后过期</a-select-option>
            <a-select-option :value="1">指定过期时间</a-select-option>
            <a-select-option :value="2">次季度首月月底失效</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col
        v-if="
          vdata.settingObject['verifiedScore'] > 0 &&
            vdata.settingObject['scoreOverType'] === 0
        "
        :span="11"
      >
        <a-form-item label="有效天数" name="scoreOverDays">
          <a-input-number
            v-model:value="vdata.settingObject['scoreOverDays']"
            :disabled="vdata.disabled"
            :precision="0"
            min="0"
            placeholder="有效天数"
            style="width: 100%"
          />
        </a-form-item>
      </a-col>
      <a-col v-if="vdata.settingObject['scoreOverType'] === 1" :span="11">
        <a-form-item label="过期时间" name="scoreOverTime">
          <a-date-picker
            v-model:value="vdata.settingObject['scoreOverTime']"
            :disabled="vdata.disabled"
            valueFormat="YYYY-MM-DD"
            :disabled-date="
              (current) => current && current < dayjs().endOf('day')
            "
            style="width: 100%"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row type="flex" justify="space-between">
      <a-col :span="11">
        <a-form-item label="是否需要网点激活" name="isNeedActivate">
          <a-radio-group
            v-model:value="vdata.settingObject['isNeedActivate']"
            :disabled="vdata.disabled"
          >
            <a-radio :value="0">否</a-radio>
            <a-radio :value="1">是</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
    </a-row>

    <a-row
      v-if="vdata.settingObject['isNeedActivate'] === 1"
      type="flex"
      justify="space-between"
    >
      <a-col :span="11">
        <a-form-item label="激活方式" name="activateType">
          <a-select
            v-model:value="vdata.settingObject['activateType']"
            :disabled="vdata.disabled"
            :options="activateTypeOptions"
            mode="multiple"
            placeholder="请选择激活方式"
            class="mt10"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row
      v-if="vdata.settingObject['isNeedActivate'] === 1"
      type="flex"
      justify="space-between"
    >
      <a-col :span="24">
        <a-form-item label="激活提示语" name="activateExplain">
          <a-textarea
            v-model:value="vdata.settingObject['activateExplain']"
            :disabled="vdata.disabled"
            :rows="4"
            placeholder="请输入激活提示语"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-col :span="24">
      <a-form-item label="发放客户限制" name="isLimitUser">
        <a-radio-group v-model:value="vdata.settingObject.isLimitUser" :disabled="vdata.disabled">
          <a-radio :value="0">不限制</a-radio>
          <a-radio :value="1">仅开启实名限制</a-radio>
          <a-radio :value="2">限制指定月资产等级</a-radio>
          <a-radio :value="3">限制指定季资产等级</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-col>
    <a-col v-if="vdata.settingObject.isLimitUser == 2 || vdata.settingObject.isLimitUser == 3" :span="24">
      <a-form-item label="发放客户等级限制" name="limitUserContent" :wrapper-col="{ span: 24 }">
        <a-checkbox-group v-model:value="vdata.settingObject['limitUserContent']" :disabled="vdata.disabled" style="width: 100%">
          <a-row>
            <a-col :span="6">
              <a-checkbox :value="1">价值</a-checkbox>
            </a-col>
            <a-col :span="6">
              <a-checkbox :value="2">金桂</a-checkbox>
            </a-col>
            <a-col :span="6">
              <a-checkbox :value="3">富嘉</a-checkbox>
            </a-col>
            <a-col :span="6">
              <a-checkbox :value="4">钻石</a-checkbox>
            </a-col>
            <a-col :span="6">
              <a-checkbox :value="5">鼎福</a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </a-form-item>
    </a-col>
    <a-col :span="24">
      <a-form-item label="是否开启回执" name="isOpenReceipt">
        <a-radio-group v-model:value="vdata.settingObject['isOpenReceipt']" :disabled="vdata.disabled">
          <a-radio :value="0">否</a-radio>
          <a-radio :value="1">是</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-col>
    <a-col :span="24">
      <a-form-item v-if="vdata.settingObject.isOpenReceipt === 1" label="回执类型" name="receiptType">
        <a-checkbox-group v-model:value="vdata.settingObject['receiptType']" :disabled="vdata.disabled" style="width: 100%" @change="changeReceiptType">
          <a-row>
            <a-col :span="8">
              <a-checkbox :value="0">基础信息（不校验）</a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox :value="1">手机银行（后校验）</a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox :value="2">快捷支付（后校验）</a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox :value="3">开卡（后校验）</a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox :value="4">提额（后校验）</a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox :value="5">养老金账户号（后校验）</a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox :value="6">商户号（后校验）</a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </a-form-item>
    </a-col>
    <a-col :span="24">
      <a-form-item v-if="vdata.settingObject.isOpenReceipt === 1 && vdata.settingObject.receiptType?.length" label="回执内容" name="receiptContent" :wrapper-col="{ span: 24 }">
        <a-table :columns="receiptContentTableColumns" :dataSource="receiptContentTableDataSource" size="small" :pagination="false" style="margin: initial;">
          <template #bodyCell="{ record, column }">
            <template v-if="column.key === 'isOpen'">
              <a-switch v-model:checked="record.isOpen" :disabled="vdata.disabled ? vdata.disabled : record.disabled" />
            </template>
            <template v-if="column.key === 'isMust' && record.isOpen">
              <a-switch v-model:checked="record.isMust" :disabled="vdata.disabled ? vdata.disabled : record.disabled" />
            </template>
            <template v-if="column.key ==='remark' &&record.isOpen">
              <div style="display: flex;align-items: center;">
                <a-tooltip v-if="column.key ==='remark' &&record.isOpen&&record.isRemark" placement="right">
                  <question-circle-outlined />
                  <template #title>
                    <div>备注输入参数：{"min":100000,"max":100000}</div>
                  </template>
                </a-tooltip>
                <a-input v-model:value="record.remark" style="margin-left: 5px;" />
              </div>
            </template>
          </template>
        </a-table>
      </a-form-item>
    </a-col>
  </a-form>
</template>


<script setup lang="ts">
import dayjs from 'dayjs'
import {reactive,ref,getCurrentInstance,watch,computed,nextTick,onMounted,} from 'vue'
import{$settingDetail}from '@/api/awardMange/coupon/index'

const stepForm1Ref = ref()
const emit = defineEmits(['sendData'])
// 定义props
const props = defineProps({
  // 奖品id
    awardId: {
    type: String,
    default:'',
  },
  // 奖品类型
  awardType: {
    type: Number,
    default:0,
  },

  awardSettingId:{
  type: String,
    default:'',
  },

    disabled:{
   type: Boolean,
    default:'',
  },
  // 从详情进入
  isDisabled:{
    type:Boolean,
    default:false
  },
  isDetail:{
    type:Boolean,
    default:false
  }

})

const vdata :any  = reactive({
  disabled:props.disabled,
    settingObject:{
    isRestrictBank: 0,  // 是否限卡支付
    periodType: 0,  // 周期性中奖限制
    everyonePeriodType: 0,  // 同一用户周期性次数限制参与
    verifiedScore: 0,
    isNeedActivate: 0,
    isEmployee:0,
    isLimitUser:0,
    limitUserContent: [],
    isOpenReceipt:0,
    receiptContent: {},
    activeMsg: 0,
    }
})


const settingRules = {
    everyoneMaxNum: [{ required: true, message: '每个用户可领取最大数量不能为空', trigger: 'blur' }],
    isLimitUser:[ { required: true, trigger: 'blur', message: '发放限制不能为空',} ],
    isOpenReceipt:[ { required: true, trigger: 'blur', message: '回执不能为空',} ],
    receiptType: [{ required: true, message: '回执类型不能为空', trigger: 'blur' }], // 回执类型
    limitUserContent:[{required: true, message: '请选择发放客户等级限制', trigger: 'blur'}],
    isRestrictBank: [{ required: true, message: '限卡支付不能为空', trigger: 'blur' }],
    periodTimes: [{ required: true, validator: periodTimesValidator },],
    everyonePeriodTimes: [{ required: true, validator: everyonePeriodTimesValidator }, ],
    verifiedScore: [ { required: true, message: '核销后奖励福分不能为空', trigger: 'blur' }, ],
    scoreOverTime: [ { required: true, message: '过期时间不能为空', trigger: 'blur' }, ],
    scoreOverDays: [ { required: true, message: '有效天数不能为空', trigger: 'blur' }, ],
    isNeedActivate: [ { required: true, trigger: 'blur', message: '请选择是否需要网点激活' }, ],
    activateType: [ { required: true, message: '激活方式不能为空', trigger: 'blur' }, ],
    activateExplain: [ { required: true, message: '激活提示语不能为空', trigger: 'blur' }, ],
    isAllocation: [ { required: true, message: '是否限制可兑换网点不能为空', trigger: 'blur', }, ],
    
    receiptContent:[{required: true, validator: () => {
      // 判断回执内容中所有选项种是否没有一个开启的
      const flag = receiptContentTableDataSource.value.find(item => item.isOpen === true)
      const deposit = receiptContentTableDataSource.value.find(item=>item.key =='deposit')
      const remark = receiptContentTableDataSource.value.find(item =>  item.key =='deposit' &&item.remark.length >0)      
      if(!flag){
        return Promise.reject('请完善回执内容')
      }
      if(!remark && deposit){
        return Promise.reject('请输入额度备注内容')
      }
      return Promise.resolve()
    }}],  
}

/**
 * 周期性中奖限制校验
 */
 function periodTimesValidator() {
  if (vdata.settingObject['periodType'] !== 0 && !vdata.settingObject['periodTimes']) {
    return Promise.reject('卡券周期性限制不能为空')
  } else {
    return Promise.resolve()
  }
}
/**
 * 周期性中奖限制校验
 */
 function everyonePeriodTimesValidator() {
  if (vdata.settingObject['everyonePeriodType'] !== 0 && !vdata.settingObject['everyonePeriodTimes']) {
    return Promise.reject('同一用户周期性次数限制不能为空')
  } else {
    return Promise.resolve()
  }
}

// 是否需要激活options
const activateTypeOptions = [
  { label: '实名认证', value: 1 },
  { label: '客户经理', value: 2 },
]


// 回执内容表格
const receiptContentTableColumns = [
  { title: '回执内容', dataIndex: 'content', key: 'content' },
  { title: '是否开启', dataIndex: 'isOpen', key: 'isOpen', align: 'center' },
  { title: '是否必填', dataIndex: 'isMust', key: 'isMust', align: 'center' },
  { title: '备注', dataIndex: 'remark', key: 'remark', align: 'center' },

]
// 回执内容表格数据
const receiptContentTableDataSource = ref([] as any[])
// 回执类型切换 根据回执类型 动态渲染回执内容表格
// 回执内容表格数据初始化
// 内容表格原始全部数组
let  receiptContentTableDataSourceOrigin = [
  { key: 'name', content: '姓名', isOpen: false, isMust: true, disabled: false, isShow: '0',remark:'' },
  { key: 'phone', content: '手机号', isOpen: false, isMust: true, disabled: false, isShow: '0',remark:'' },
  { key: 'idCard', content: '身份证号', isOpen: false, isMust: true, disabled: false, isShow: '0',remark:'' },
  { key: 'address', content: '地址', isOpen: false, isMust: true, disabled: false, isShow: '0',remark:'' },
  { key: 'bankCard', content: '银行卡号', isOpen: false, isMust: false, disabled: false, isShow: '1,2,3,4',remark:'' },
  { key: 'bankImg', content: '银行卡照片', isOpen: false, isMust: false, disabled: false, isShow: '1,2,3,4',remark:'' },
  { key: 'date', content: '日期', isOpen: false, isMust: false, disabled: false, isShow: '3,4',remark:'' },
  { key: 'deposit', content: '额度', isOpen: true, isMust: true, disabled: true, isShow: '4',remark:'',isRemark:true },//isRemark用来做是否显示填写内容
  { key: 'pension', content: '养老金账户号', isOpen: true, isMust: true, disabled: true, isShow: '5' ,remark:''},
  { key: 'mchNo', content: '商户号', isOpen: true, isMust: true, disabled: true, isShow: '6',remark:'' },
] as any


function changeReceiptType(e){  // [0,1]
  if(e.includes(0) && receiptContentTableDataSource.value.length > 4){ // 之前内容已包含基础信息，在切换回执类型的时候不再调整基础信息
    const BaseReceiptContentTableDataSource = receiptContentTableDataSource.value.filter(item => item.isShow === '0')
    receiptContentTableDataSourceOrigin.forEach(origin => {
      if(origin.isShow !== '0' && e.some(value => origin.isShow.split(',').map(Number).includes(value))){
        BaseReceiptContentTableDataSource.push(origin)
      }
    })
    receiptContentTableDataSource.value = BaseReceiptContentTableDataSource
  }else{
    receiptContentTableDataSource.value = receiptContentTableDataSourceOrigin.filter(origin => e.some(value => origin.isShow.split(',').map(Number).includes(value)))
    if(e.includes(4)){
    // 选择了提额
    }
  }
  
}

const sendToParent = () => {
  // 2. 触发事件，传递数据
  emit('sendData', { childrensettingObject: vdata.settingObject })
}

function validate (){
  return stepForm1Ref.value.validate()
}
onMounted(()=>{
if(props.awardSettingId){
getSettingDetail(props.awardSettingId)
}

})

// 查setting配置的详情

  function  getSettingDetail(awardSettingId){
      $settingDetail({awardSettingId:awardSettingId })
      .then((res) => {
        // 拿到后端返回的setting信息，进行处理回显给页面
        const result = res
      vdata.settingObject.everyoneMaxNum = result.everyoneMaxNum
        // 卡卷周期性中奖限制
      vdata.settingObject.periodType = result.periodType
      vdata.settingObject.periodTimes = result.periodTimes
      // 同一用户周期性次数限制 
      vdata.settingObject.everyonePeriodType = result.everyonePeriodType
      vdata.settingObject.everyonePeriodTimes = result.everyonePeriodTimes
        // 核销后奖励福分
      vdata.settingObject.verifiedScore = result.verifiedScore
      // 福分规则类型
      vdata.settingObject.scoreOverType = result.scoreOverType
      // 过期时间
      
      vdata.settingObject.scoreOverTime =result.scoreOverTime
      // 有效天数
      vdata.settingObject.scoreOverDays = result.scoreOverDays
      // 是否需要网点激活
      vdata.settingObject.isNeedActivate = result.isNeedActivate
      // 激活方式
      if(vdata.settingObject.isNeedActivate==1){
       vdata.settingObject.activateType = result.activateType.split(',').map(Number)
      }
      // 激活提示语  activateExplain
         vdata.settingObject.activateExplain = result.activateExplain
        //  发放客户限制 isLimitUser
         vdata.settingObject.isLimitUser = result.isLimitUser
        //  发放客户资产等级 limitUserContent        
        vdata.settingObject.limitUserContent = result.limitUserContent
        // 是否限制卡卷回执
      vdata.settingObject.isOpenReceipt = res.isOpenReceipt
      // 回执类型
      vdata.settingObject.receiptType = res.receiptType
          if(vdata.settingObject.isOpenReceipt === 1 && res.receiptContent){
          // 处理回执内容
          const receiptContentObj = JSON.parse(res.receiptContent)
            // console.log('receiptContentTableDataSource.value处理钱',receiptContentTableDataSource.value)

          receiptContentTableDataSourceOrigin.forEach(origin => {
            if(receiptContentObj[origin.key]){
              receiptContentTableDataSource.value.push({ key: origin.key, content: origin.content, isOpen: true, isMust: receiptContentObj[origin.key].isMust, disabled: receiptContentObj[origin.key].disabled, isShow: receiptContentObj[origin.key].isShow ,remark:receiptContentObj[origin.key].remark})
            }else{
              if(origin.isShow !== '0' && vdata.settingObject.receiptType.includes(0)){
                receiptContentTableDataSource.value.push(origin)
              }
            }
            
          })
         
        }

      // 回执类型内容的处理

      })
  }

function  changehadleSaveStting(){  
  const uploadObject = JSON.parse(JSON.stringify(vdata.settingObject)) 
  const {isNeedActivate} = uploadObject
   // 是否需要网点激活数据处理
  if (isNeedActivate === 1) {
    uploadObject.activateType = uploadObject.activateType.join()
    
  } else {
    uploadObject.activateType = ''
    uploadObject.activateExplain = ''
  } 

  // // 客户限制处理
  // if((uploadObject.isLimitUser === 2 || uploadObject.isLimitUser === 3) && uploadObject.limitUserContent?.length){
  //   console.log('uploadObject.limitUserContent',uploadObject.limitUserContent)
    
  //   uploadObject.limitUserContent = uploadObject.limitUserContent.map(item => item).join(',')
  // }else{
  //   uploadObject.limitUserContent = ''
  // }

 // 回执类型处理

  if(uploadObject.isOpenReceipt === 1 && uploadObject.receiptType?.length){
    if(Object.prototype.toString.call(uploadObject.receiptType) === '[object String]'){
        console.log('不做任何处理')
    }else{
    uploadObject.receiptType = uploadObject.receiptType.join()

    }
  }else{
    uploadObject.receiptType = ''
  }
  
  const receiptContentTableDataSourceFilter = receiptContentTableDataSource.value.filter(item => item.isOpen) // 过滤开启的回执内容
  if(uploadObject.isOpenReceipt === 1 && uploadObject.receiptType?.length && receiptContentTableDataSourceFilter?.length){
    // 回执内容处理
    if(uploadObject.receiptContent==undefined){
          uploadObject.receiptContent = {}
        }else{

        }
        
    receiptContentTableDataSourceFilter.forEach(item => {
      uploadObject.receiptContent[item.key] = { isMust: item.isMust, disabled: item.disabled, isShow: item.isShow,remark:item.remark }
    })
    uploadObject.receiptContent = JSON.stringify(uploadObject.receiptContent)
  }else{
    uploadObject.receiptContent = null
  }
return uploadObject

}


defineExpose({
 validate,
changehadleSaveStting,

})
// 
watch(
  () => vdata.settingObject,
  (newVal, oldVal) => {
    sendToParent()
  },
  { deep: true } // 启用深度监听
)
</script>